import sys, os
import qdarkstyle
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5 import QtWidgets as QtW
from PyQt5.QtWidgets import *
import ui_mainWin
import codeEdit
import win32api, subprocess, yaml


class Gui(ui_mainWin.Ui_MainWindow, QtW.QMainWindow):
	def __init__(self,file=None):
		super().__init__()
		self.windowList = []
		QFontDatabase.addApplicationFont('./font/CascadiaCodePL')
		self.setupUi(self)
		self.showMaximized()
		self.codeEdit = codeEdit.CodeEditor()
		self.codeEdit.setEdgeColumn(self.width())
		self.codeEdit.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5())
		self.setCentralWidget(self.codeEdit)
		self.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5())
		self.setup()
		if file:
			self.openfile(file)

	def setup(self):
		self.opendfile = '';
		self.actionNew.triggered.connect(self.newfile)
		self.actionOpen.triggered.connect(self.DLGopenfile)
		self.actionSave.triggered.connect(self.DLGsavefile)
		self.actionCompile.triggered.connect(self.compileCpp)
		self.actionRun.triggered.connect(self.runCpp)

	def compileCpp(self):
		if(self.opendfile):
			with open('config/compilerConfig.yml', 'rb')as f:
				res = yaml.load(f, Loader=yaml.FullLoader)
			cmd=res['compile_cmd'].replace(r'{filename}',self.opendfile)
			cmd=cmd.replace(r'{exename}',os.path.splitext(self.opendfile)[0]+'.exe')
			with open('compile_temp.bat','w',encoding='utf-8') as fp:
				fp.write('@echo off\n')
				fp.write(cmd)
				fp.write('\necho Compile Finished:'+os.path.splitext(self.opendfile)[0]+'.exe')
				fp.write('\npause')
			win32api.ShellExecute(
			0, 'open', 'compile_temp.bat', '', '', 1)
		else:
			QtW.QMessageBox.critical(self,'编译',f"请保存文件后再编译")
			self.DLGsavefile()

	def runCpp(self):
		if not self.opendfile:
			QtW.QMessageBox.critical(self,'运行',f"请保存文件后再运行")
			self.DLGsavefile()
		with open('config/compilerConfig.yml', 'rb')as f:
			res = yaml.load(f, Loader=yaml.FullLoader)
			cmd = res['run_cmd'].replace(r'{filename}',self.opendfile)
			with open('run_temp.bat','w',encoding='utf-8') as fp:
				fp.write('@echo off\n')
				fp.write(cmd)
				fp.write('\necho\\')
				fp.write('\necho --------------------------')
				fp.write('\necho Finished')
				fp.write('\npause')
			win32api.ShellExecute(
			0, 'open', 'run_temp.bat', '', '', 1)

	def DLGopenfile(self):
		file, filetype = QtW.QFileDialog.getOpenFileName(self, "打开文件",
		'C:\\',  # 起始路径
		"C++ Files (*.cpp;*.cc;*.c++;*.hpp;*.hh;*.hxx;*.h++;*.h;*.ii;*.c)")   # 设置文件扩展名过滤, 用分号间隔
		if(file):
			if self.opendfile:
				win = Gui(file)
				self.windowList.append(win)
				win.show()
			else:
				self.openfile(file)

	def DLGsavefile(self):
		if not self.opendfile:
			file, filetype = QtW.QFileDialog.getSaveFileName(self,"保存文件",
			'C:\\',  # 起始路径
			"C++ Files (*.cpp;*.cc;*.c++;*.hpp;*.hh;*.hxx;*.h++;*.h;*.ii;*.c)")   # 设置文件扩展名过滤,用双分号间隔
			if file:
				with open(file,'w',encoding='utf-8') as fp:
					fp.write(self.codeEdit.text())
					self.opendfile = file;
		else:
			with open(self.opendfile, 'w',encoding='utf-8') as fp:
				fp.write(self.codeEdit.text())


	def newfile(self):
		self.DLGsavefile()
		self.opendfile = ''
		self.codeEdit.setText('')
			

	def openfile(self,filename):
		if(os.path.exists(filename)):
			try:
				with open(filename,'r', encoding='utf-8') as fp:
					data = fp.read()
				self.codeEdit.setText(data)
				self.opendfile = filename;
			except Exception as e:
				QtW.QMessageBox.critical(self,'打开文件错误',f"打开文件 “{filename}” 时出现错误：\n{str(e)}")
		else:
			QtW.QMessageBox.critical(self,'打开文件错误',f"打开文件 “{filename}” 时出现错误：\n文件不存在")


if __name__ == '__main__':
	app = QtW.QApplication(sys.argv)
	mainwin = Gui()
	mainwin.show()
	sys.exit(app.exec_())
